package com.example.library.service;

import com.example.library.model.Book;
import com.example.library.repository.BookRepository;
import com.example.library.repository.BorrowRecordRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookService {
    private final BookRepository bookRepository;
    private final BorrowRecordRepository borrowRecordRepository;

    public BookService(BookRepository bookRepository, BorrowRecordRepository borrowRecordRepository) {
        this.bookRepository = bookRepository;
        this.borrowRecordRepository = borrowRecordRepository;
    }

    public List<Book> getAllBooksWithBorrowRecords() {
        List<Book> books = bookRepository.findAll();
        books.forEach(book -> {
            book.setBorrowRecords(borrowRecordRepository.findByBook(book));
        });
        return books;
    }

    public List<Book> searchBooks(String keyword) {
        return bookRepository.findAll().stream()
                .filter(book ->
                        book.getTitle().contains(keyword) ||
                                book.getAuthor().contains(keyword) ||
                                book.getIsbn().contains(keyword))
                .collect(Collectors.toList());
    }
}